package cn.mabach.oauth2.qq;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
public class QQAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    private String usernameParameter = "qq";

    private boolean postOnly = false;

    public QQAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/qq", "GET"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = this.obtainUsername(request);

            if (username == null) {
                username = "";
            }



            username = username.trim();
//            封装未认证的将QQAuthenticationToken并设置到QQAuthenticationToken父类方法的Details中
            QQAuthenticationToken qqAuthenticationToken = new QQAuthenticationToken(username);

            this.setDetails(request, qqAuthenticationToken);


            return this.getAuthenticationManager().authenticate(qqAuthenticationToken);
        }
    }



    @Nullable
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(this.usernameParameter);
    }

//    set方法，把设置请求详情设置到smsCodeAuthenticationToken，中比如ip,sessionId
    protected void setDetails(HttpServletRequest request, QQAuthenticationToken qqAuthenticationToken) {
        qqAuthenticationToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }


    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return this.usernameParameter;
    }


}